package com.walle.gatewayserver.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;


import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import com.netflix.util.Pair;
import com.netflix.zuul.context.RequestContext;

public class GetResponseBodyUtil {

	public static String getResponseBody(RequestContext ctx) throws IOException{
		
		
		String body = ctx.getResponseBody();
		if(StringUtils.isEmpty(body)) {
			
			List<Pair<String,String>> l = ctx.getZuulResponseHeaders();
			boolean gzip =false;
			boolean file = false;
			if(!CollectionUtils.isEmpty(l)) {
				for (Pair<String, String> pair : l) {
					
					if("gzip".equalsIgnoreCase(pair.second())) {
						l.remove(pair);
						gzip=true;
//						break;
					}
					
					if("application/octet-stream".equalsIgnoreCase(pair.second())||StringUtils.startsWithIgnoreCase(pair.second(), "attachment;")) {
								
						file=true;
//						break;
					}
				}
			}
			
			if(!file) {
				InputStream stream = ctx.getResponseDataStream();
				if(gzip) {
					body = GzipUtil.uncompress(stream, "utf-8");
				}else {
					body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
				}
			}
		}
		

		return body;

		
	}
	
}
